package com.yangchuang.openpicture;

import com.yangchuang.openpicture.constant.FileUploadConstants;
import com.yangchuang.openpicture.constant.ThreadLocalConstants;
import com.yangchuang.openpicture.service.OSSService;
import com.yangchuang.openpicture.service.PictureService;
import com.yangchuang.openpicture.util.BaseContext;
import com.yangchuang.openpicture.util.ImageDimensionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

import java.io.File;

@Service
@RequiredArgsConstructor
public class getdata {

    private final OSSService ossService;
    private final PictureService pictureService;

    // 自定义 MultipartFile 类
    private static class SimpleMultipartFile implements MultipartFile {
        private final String name;
        private final String originalFilename;
        private final String contentType;
        private final byte[] content;

        public SimpleMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getOriginalFilename() {
            return originalFilename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public java.io.InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
            Files.write(dest.toPath(), content);
        }
    }

    public void batchUploadImages() throws IOException {
        // 设置 userid 为 1
        BaseContext.set(ThreadLocalConstants.USER_ID, "1");

        // 扫描目录 D:\sousuo\data\true
        Path directory = Paths.get("D:\\sousuo\\data\\true");
        if (!Files.exists(directory)) {
            System.out.println("目录不存在：" + directory);
            return;
        }

        Files.walk(directory)
            .filter(Files::isRegularFile)
            .filter(this::isImageFile)
            .forEach(path -> {
                try {
                    uploadSingleImage(path);
                } catch (Exception e) {
                    System.err.println("上传失败：" + path + ", 错误：" + e.getMessage());
                }
            });
    }

    private void uploadSingleImage(Path path) throws IOException {
        String filename = path.getFileName().toString();
        byte[] bytes = Files.readAllBytes(path);
        long fileSize = bytes.length;
        String contentType = getContentType(path);
        MultipartFile file = new SimpleMultipartFile(filename, filename, contentType, bytes);

        // 获取尺寸
        int[] dimensions = ImageDimensionUtils.getDimensions(bytes);
        int width = dimensions[0];
        int height = dimensions[1];

        // 上传到 OSS
        String objectName = ossService.uploadFile(file, FileUploadConstants.IMAGE);
        String publicUrl = ossService.getSignedUrlByObjectName(objectName);

        // 插入数据库
        pictureService.insertPicture(fileSize, publicUrl, 0L, filename, "", Collections.emptyList(), width, height);
        System.out.println("上传成功：" + filename);
    }

    private boolean isImageFile(Path path) {
        String filename = path.getFileName().toString().toLowerCase();
        return filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png") || filename.endsWith(".gif");
    }

    private String getContentType(Path path) {
        String filename = path.getFileName().toString().toLowerCase();
        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (filename.endsWith(".png")) {
            return "image/png";
        } else if (filename.endsWith(".gif")) {
            return "image/gif";
        }
        return "application/octet-stream";
    }
}
